package Downloader

import (
	"fmt"
	"sync/atomic"
	"time"
)

type Progress struct {
	bytesUptoNow int64
	timerTime    time.Duration
	fileLength   int64
}

func NewProgress(fileLength int64) (r *Progress) {
	r = new(Progress)
	r.fileLength = fileLength
	r.timerTime = time.Second * 5
	return
}

func (this *Progress) Show() {
	percent := float64(this.bytesUptoNow) / float64(this.fileLength) * 100
	fmt.Printf("%.2f%% Completed.\n", percent)
}

func (this *Progress) startTimer() {
	ch := make(chan byte)
	go func(c chan byte) {
		select {
		case <-time.After(this.timerTime):
			this.Show()
			close(ch)
			go this.startTimer()
		case <-ch:
		}
	}(ch)
}

func (this *Progress) Increase(bytes int) {
	atomic.AddInt64(&this.bytesUptoNow, int64(bytes))
}

func (this *Progress) AutomaticallyShow() {
	go this.startTimer()
}
